package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.CalendarUtils;
import cc.linker.steplink.crm.merchanth5.dao.ScoreActiveCacheDao;
import cc.linker.steplink.crm.merchanth5.dao.SurvivalPushDao;
import cc.linker.steplink.crm.merchanth5.dao.VipCustomerLogDao;
import cc.linker.steplink.crm.merchanth5.service.redis.ScoreActiveCacheService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SurvivalPushService {

    @Autowired
    private SurvivalPushDao survivalPushDao;

    @Autowired
    private MqTimeService mqTimeService;

    @Value("${casclient.clientHost}")
    private String clientHost;

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private ScoreActiveCacheDao scoreActiveCacheDao;

    @Autowired
    private ScoreActiveCacheService scoreActiveCacheService;

    @Autowired
    private HttpService httpService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private VipCustomerLogDao vipCustomerLogDao;

    @Value("${system.scrm.defimg}")
    private String defimg;

    /**
     * @Description: 方法定义描述
     * @Param: customerId  用户id
     * @Param: logId  日志id
     * @Param: action 行为
     * @Param: actionTime 行为时间
     * @Param: lastInteractionTime 最后互动时间
     * @Param: orgId 机构id
     * @Return: void
     * @Author: ch
     * @Date: 2020/4/21 18:32
     * @Version:
     **/
    public void setPushSurvival(String customerId,String logId,String action,String actionTime,String lastInteractionTime,String orgId,String articleId,String eventKey){
        LOGGER.info("促活参数:customerId--> "+customerId+"  logId-->"+logId+" action-->"+action+" actionTime-->"+actionTime
        +" lastInteractionTime-->"+lastInteractionTime+" orgId-->"+orgId+" articleId-->"+articleId+" eventKey-->"+eventKey);
        Integer trigger = 1;
        if("offlineTest".equals(action)){
            trigger=2;
        }else if("subscribe".equals(action)){
            if ("[ ]".equals(eventKey) || "[]".equals(eventKey) || eventKey == null){
                trigger=9;
            }else {
                trigger=10;
            }
        }else if("SCAN".equals(action)){
            trigger=8;
        }else if("onlineFinish".equals(action)){
            trigger=4;
        }else if("offlineFinish".equals(action)){
            trigger=5;
        }else if("readNews".equals(action)){
            trigger=6;
            if(StringUtils.isEmpty(articleId)){
                return;
            }
        }else if("CLICK".equals(action) || "click".equals(action) ){
            trigger=7;
            if(StringUtils.isEmpty(articleId)){
                return;
            }
        }
        Map map = new HashMap<>();
        map.put("actionTime",actionTime);
        map.put("trigger",trigger);
        map.put("orgId",orgId);
        if(trigger==6){
            map.put("articleId",articleId);
        }
        if(trigger==7){
            map.put("eventKey",articleId);
        }
        if(trigger==8){
            map.put("eventKey",articleId);
        }

        if(trigger==10){
            map.put("eventKey", eventKey.replace("qrscene_", ""));
        }

        //获取符合促活列表（同时剔除过期的action+过期时间大于当前时间）
        List<Map> survivalTouchs = survivalPushDao.getSurvivalTouchs(map);
        if(survivalTouchs!=null && survivalTouchs.size()>0){
            for (Map survival : survivalTouchs){
                survival.put("actionTime",actionTime);
                survival.put("action",action);
                survival.put("customerId",customerId);
                survival.put("logId",logId);
                survival.put("lastInteractionTime",lastInteractionTime);
                survival.put("orgId",orgId);
                //是否插入过智能促活用户表
                Integer touchCount = survivalPushDao.getTouchCount(survival);
                if(touchCount==0){
                    LOGGER.info("============插入促活日志");
                    //没有插入过先插入一条触发记录
                    survival.put("isPush",0);
                    survivalPushDao.insertTouchCount(survival);
                    //修改智能促活表用户触发次数
                    survivalPushDao.addTouchNum(survival);
                }
            }
        }
        //获取符合促活列表（同时剔除过期的action+过期时间大于当前时间）
        List<Map> survivals = survivalPushDao.getSurvivals(map);
        //遍历创建队列
        if(survivals!=null && survivals.size()>0){
            LOGGER.info("============存在符合条件的促活");
            for (Map survival : survivals){
                survival.put("actionTime",actionTime);
                survival.put("action",action);
                survival.put("customerId",customerId);
                survival.put("logId",logId);
                survival.put("lastInteractionTime",lastInteractionTime);
                survival.put("orgId",orgId);
                //是否可以重复推送
                Integer canrepeat = 0;
                if(!StringUtils.isEmpty(survival.get("canrepeat"))){
                    canrepeat = Integer.valueOf(survival.get("canrepeat").toString());
                }
                //是否push过智能促活用户表
                Map maps = new HashMap<>();
                String survivalId = "";
                if(!StringUtils.isEmpty(survival.get("survivalId"))){
                    survivalId = survival.get("survivalId").toString();
                }
                maps.put("survivalId",survivalId);
                maps.put("customerId",customerId);
                Integer pushCount = survivalPushDao.getPushCount(maps);
                if(pushCount == 0 || canrepeat==1){
                    maps.put("logId",logId);
                    //缓存中如果有一条正在推送的(直接结束)
                    String key = "pushing:param_" + logId+survivalId+customerId;
                    String pushing = stringRedisTemplate.opsForValue().getAndSet(key,"pushing");
                    if("pushing".equals(pushing)){
                        return;
                    }
                    //如果不能重复推送 缓存中有一条正在推送的(直接结束)
                    String keys = "pushings:param_" + survivalId+customerId;
                    String pushings = stringRedisTemplate.opsForValue().getAndSet(keys,"pushings");
                    if(canrepeat==0 && "pushings".equals(pushings)){
                        return;
                    }
                    if(pushCount==1){
                        //如果是只有一条
                        Integer pushThisCount = survivalPushDao.getPushCount(maps);
                        //如果是本条已推送也结束
                        if(pushThisCount==1){
                            return;
                        }
                    }
                    //没有push过或者可以重复推送
                    //计算推送时间
                    //获取促活策略内容列表
                    List<Map> survivalContents = survivalPushDao.getSurvivalContents(survival);
                    if(survivalContents!=null && survivalContents.size()>0){
                        for(Map survivalContent : survivalContents){
                            LOGGER.info("============插入促活内容  "+JSON.toJSONString(survivalContent));
                            Long delaytime = 0l;
                            Integer sendTime = 0;
                            if(!StringUtils.isEmpty(survivalContent.get("sendTime"))){
                                sendTime = Integer.valueOf(survivalContent.get("sendTime").toString());
                            }
                            //计算时间
                            //计算时间（区间内的时间）
                            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date now =  new Date();
                            Date touchTime = this.getDate(survival,sendTime);
                            LOGGER.info("当前时间为====》"+sdf2.format(now));
                            LOGGER.info("发送时间为====》"+sdf2.format(touchTime));
                            delaytime = touchTime.getTime()-now.getTime();
                            if(!StringUtils.isEmpty(survivalContent.get("type"))){
                                Integer type = Integer.valueOf(survivalContent.get("type").toString());
                                survival.put("type",type);
                            }
                            if(!StringUtils.isEmpty(survivalContent.get("survivalContentId"))){
                                String survivalContentId = survivalContent.get("survivalContentId").toString();
                                survival.put("survivalContentId",survivalContentId);
                            }
                            //创建队列
                            LOGGER.info("============创建促活队列剩余时间》"+delaytime);
                            JSONObject jsonObject = (JSONObject) JSONArray.toJSON(survival);

                        }
                    }


                }
            }
        }
    }

    /**
     * 发送push（队列中取出）
     * @param msg
     * @param : survivalId 策略主键
     * @param : expirationTime 过期时间（小时）
     * @param : canrepeat 是否可重复推送 0不可以 ；1可以
     * @param : type 促活策略内容 类型
     *         1图片、2文本、3视频、4音频、5商品、6知识商品、7文章、8报名、9智能图片、10智能文本、
     *         11智能视频、12智能音频、13智能商品、14智能知识商品、15智能文章、16智能报名
     * @param : survivalContentId 内容ID
     * @Param : customerId  用户id
     * @Param : logId  日志id
     * @Param : action 行为
     * @Param : actionTime 行为时间
     * @Param : lastInteractionTime 最后互动时间
     * @Param : orgId 机构id
     *
     */
    public void process(String msg) {
        try {
            LOGGER.info("促活队列接收时间: " + LocalDateTime.now() + " msg内容：" + msg);
            Object parse = JSON.parse(msg);
            if(parse==null){
                return;
            }
            Map ret = (Map) parse;
            //获取促活策略内容值列表
            List<String> survivalContentValues = survivalPushDao.getSurvivalContentValues(ret);
            Integer type = 1;
            if(!StringUtils.isEmpty(ret.get("type"))){
                type = Integer.valueOf(ret.get("type").toString());
            }
            String orgId = "";
            if(!StringUtils.isEmpty(ret.get("orgId"))){
                orgId = ret.get("orgId").toString();
            }
            String customerId="";
            if(!StringUtils.isEmpty(ret.get("customerId"))){
                customerId = ret.get("customerId").toString();
            }
            String res ="";
            if(type==17 && survivalContentValues!=null && survivalContentValues.size()>1){
                Random random = new Random();
                int n = random.nextInt(survivalContentValues.size());
                Map resMap = this.getValue(survivalContentValues.get(n),type,orgId);
                LOGGER.info("push发送前参数为========》"+JSON.toJSONString(resMap));
                if("1".equals(resMap.get("pushType"))){
                    resMap.remove("pushType");
                    res = this.resMap(resMap,customerId);
                }else if("2".equals(resMap.get("pushType"))){
                    resMap.remove("pushType");
                    res = this.newsResMap(resMap,customerId);
                }
            }
            if(survivalContentValues!=null && survivalContentValues.size()==1){
                Map resMap = this.getValue(survivalContentValues.get(0),type,orgId);
                LOGGER.info("push发送前参数为========》"+JSON.toJSONString(resMap));
                if("1".equals(resMap.get("pushType"))){
                    resMap.remove("pushType");
                    res = this.resMap(resMap,customerId);
                }else if("2".equals(resMap.get("pushType"))){
                    resMap.remove("pushType");
                    res = this.newsResMap(resMap,customerId);
                }
            }
            if(type!=17 && survivalContentValues!=null && survivalContentValues.size()>1){
                List<String> userLabelIds = survivalPushDao.getUserLabelIdsByCustomerId(customerId);
                Map resMap = new HashMap<>();
                int count = 0;
                int resCount = 0;
                for (String value : survivalContentValues){
                    Map forMap = this.getValue(value,type,orgId);
                    if(forMap!=null){
                        if(resMap.size()==0){
                            resMap = forMap;
                        }
                        if(forMap.get("labelIds")!=null){
                            List<String> thisLabelIds =(List<String>) forMap.get("labelIds");
                            if(thisLabelIds!=null){
                                resCount = this.getCount(userLabelIds,thisLabelIds);
                                if(resCount>count){
                                    count = resCount;
                                    resMap=forMap;
                                }else if(resCount==count){
                                    int[] i = {1,2};
                                    Random random = new Random();
                                    int r = random.nextInt(i.length);
                                    int a = i[r];
                                    if(a==1){
                                        resMap=forMap;
                                    }
                                }
                            }
                        }
                    }
                }
                LOGGER.info("push发送前参数为========》"+JSON.toJSONString(resMap));
                if("1".equals(resMap.get("pushType"))){
                    resMap.remove("pushType");
                    res = this.resMap(resMap,customerId);
                }else if("2".equals(resMap.get("pushType"))){
                    resMap.remove("pushType");
                    res = this.newsResMap(resMap,customerId);
                }
            }

            if(StringUtils.isEmpty(res)){
                LOGGER.error("矩阵调用返回空");
            }else {
                Object obj = JSON.parse(res);
                if(obj!=null){
                    Map retMap = (Map) obj;
                    String code = "";
                    if(retMap.get("errcode")!=null){
                        code = retMap.get("errcode").toString();
                    }
                    LOGGER.info("推送后参数"+res);
                    LOGGER.info("推送后转化参数"+JSON.toJSONString(retMap));
                    if("200".equals(code)){
                        LOGGER.info("修改推送");
                        LOGGER.info("推送后转化参数"+JSON.toJSONString(ret));
                        //push成功（修改推送状态）
                        //获取已推送条数
                        Integer count = survivalPushDao.getPushCount(ret);
                        if(count == 0){
                            survivalPushDao.updateIsPush(ret);
                            //push成功（修改推送状态数据）
                            survivalPushDao.updatePushNum(ret);
                        }

                        String logId ="";
                        if(!StringUtils.isEmpty(ret.get("logId"))){
                            logId = ret.get("logId").toString();
                        }
                        String survivalId ="";
                        if(!StringUtils.isEmpty(ret.get("survivalId"))){
                            survivalId = ret.get("survivalId").toString();
                        }
                        String key = "pushing:param_" + logId+survivalId+customerId;
                        stringRedisTemplate.delete(key);
                        //如果不能重复推送 缓存中有一条正在推送的(直接结束)
                        String keys = "pushings:param_" + survivalId+customerId;
                        stringRedisTemplate.delete(keys);
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error("队列接收异常！", e);
        }
    }


    public Integer getCount(List<String> list1,List<String> list2){
        List<String> list3 = new ArrayList<String>();
        list3.addAll(list1);
        list3.retainAll(list2);
        return list3==null?0:list3.size();
    }

    /**
     * 非文章push
     * @param map
     * @param customerId
     * @return
     */
    public String resMap( Map map,String customerId){
        //直接发送
        Map tokenMap = survivalPushDao.getTokenAndOpenId(customerId);
        if(tokenMap==null){
            return "";
        }
        map.put("openid",tokenMap.get("openId"));
        map.put("token", tokenMap.get("token"));
        map.put("action", "activeReply");
        map.remove("labelIds");
        String result="";
        try {
            LOGGER.info("调用矩阵发送push====>参数为==》"+JSON.toJSONString(map));
            result = httpService.doPost(systemProperties.getWxpushurl(), JSON.toJSONString(map));
        } catch (Exception e) {
            LOGGER.error("矩阵调用异常");
        }
        return result;
    }

    /**
     * 文章push
     * @param : map=>desc 文章简介
     * @param :      image 分享图片地址
     * @param :      title 	文章标题
     * @param :      url 	文章url
     * @param customerId
     * @return
     */
    public String newsResMap( Map map,String customerId){
        //直接发送
        Map tokenMap = survivalPushDao.getTokenAndOpenId(customerId);
        if(tokenMap==null){
            return "";
        }
        if(StringUtils.isEmpty(map.get("desc"))){
            map.put("desc"," ");
        }
        map.put("openid",tokenMap.get("openId"));
        map.put("token", tokenMap.get("token"));
        map.put("action", "replayNews");
        map.remove("labelIds");
        String result="";
        try {
            LOGGER.info("调用矩阵发送push====>参数为==》"+JSON.toJSONString(map));
            result = httpService.doPost(systemProperties.getWxpushurl(), JSON.toJSONString(map));
        } catch (Exception e) {
            LOGGER.error("矩阵调用异常");
        }
        return result;
    }


    /**
     * 根据 type获取发送push信息
     * @param value
     * @param type
     *         1图片、2文本、3视频、4音频、5商品、6知识商品、7文章、8报名、9智能图片、10智能文本、
     *         11智能视频、12智能音频、13智能商品、14智能知识商品、15智能文章、16智能报名、17智能魔盒
     * @return val，type，labelIds
     */
    public Map getValue(String value,Integer type,String orgId){
        Map<String,Object> result = new HashMap();
        Map maps;
        Map ret;
        Integer goodsType = 1;
        if(type==17){
            type = this.getTypeByValue(value);
        }
        List<String> labelIdsArr = new ArrayList<String>();
        switch (type){
            case 1 :
                Object parse1 = JSON.parse(value);
                if(parse1!=null){
                    ret =(Map) parse1;
                    result.put("val",ret.get("value"));
                }
                result.put("type","image");
                result.put("pushType","1");
                break;
            case 2 :
                Object parse2 = JSON.parse(value);
                if(parse2!=null){
                    ret =(Map) parse2;
                    result.put("val",ret.get("value"));
                }
                result.put("type","text");
                result.put("pushType","1");
                break;
            case 3 :
                Object parse3 = JSON.parse(value);
                if(parse3!=null){
                    ret =(Map) parse3;
                    result.put("val",ret.get("value"));
                }
                result.put("type","video");
                result.put("pushType","1");
                break;
            case 4 :
                Object parse4 = JSON.parse(value);
                if(parse4!=null){
                    ret =(Map) parse4;
                    result.put("val",ret.get("value"));
                }
                result.put("type","voice");
                result.put("pushType","1");
                break;
            case 5 :
                Object parse5 = JSON.parse(value);
                if(parse5!=null){
                    ret =(Map) parse5;
                    if(StringUtils.isEmpty(ret.get("goodsId")) &&  !StringUtils.isEmpty(ret.get("id"))){
                        ret.put("goodsId",ret.get("id"));
                    }
                    maps =survivalPushDao.getGoodsInfo(ret);
                    if(maps!=null){
                        if(!StringUtils.isEmpty(maps.get("goodsType"))){
                            goodsType = Integer.valueOf(maps.get("goodsType").toString());
                        }
                        value = this.getPagePathByGoodsType(maps,goodsType,orgId);
                        result.put("url",value);
                        result.put("title",maps.get("title"));
                        result.put("image",maps.get("image"));
                        result.put("desc",maps.get("desc"));
                    }
                }
                result.put("pushType","2");
                break;
            case 6 :
                Object parse6 = JSON.parse(value);
                if(parse6!=null){
                    ret =(Map) parse6;
                    if(StringUtils.isEmpty(ret.get("goodsId")) && !StringUtils.isEmpty(ret.get("id"))){
                        ret.put("goodsId",ret.get("id"));
                    }
                    maps = survivalPushDao.getGoodsInfo(ret);
                    if(maps!=null){
                        if(!StringUtils.isEmpty(maps.get("goodsType"))){
                            goodsType = Integer.valueOf(maps.get("goodsType").toString());
                        }
                        value = this.getPagePathByGoodsType(maps,goodsType,orgId);
                        result.put("url",value);
                        result.put("title",maps.get("title"));
                        result.put("image",maps.get("image"));
                        result.put("desc",maps.get("desc"));
                    }
                }
                result.put("pushType","2");
                break;
            case 7 :
                Object parse7 = JSON.parse(value);
                if(parse7!=null){
                    ret =(Map) parse7;
                    String shortUrl="";
                    String articleId = "";
                    if(!StringUtils.isEmpty(ret.get("shortUrl"))){
                        shortUrl = ret.get("shortUrl").toString();
                    }
                    if(!StringUtils.isEmpty(ret.get("articleId"))){
                        articleId = ret.get("articleId").toString();
                    }
                    if("".equals(articleId) && !StringUtils.isEmpty(ret.get("id"))){
                        articleId = ret.get("id").toString();
                    }
                    Map articleMap7= this.getArticleById(articleId);
                    result.put("url",shortUrl);
                    result.put("title",articleMap7.get("title"));
                    result.put("image",articleMap7.get("image"));
                    result.put("desc",articleMap7.get("desc"));
                    if(StringUtils.isEmpty(shortUrl)){
                        result.put("url",articleMap7.get("shortUrl"));
                    }
                }
                result.put("pushType","2");
                break;
            case 8 :
                Object parse8 = JSON.parse(value);
                if(parse8!=null){
                    ret =(Map) parse8;
                    if(StringUtils.isEmpty(ret.get("enrollId")) && !StringUtils.isEmpty(ret.get("id"))){
                        ret.put("enrollId",ret.get("id"));
                    }
                    maps = survivalPushDao.getEnrollInfo(ret);
                    if(maps!=null){
                        goodsType = 5;
                        value = this.getPagePathByGoodsType(maps,goodsType,orgId);
                        result.put("url",value);
                        result.put("title",maps.get("title"));
                        result.put("image",maps.get("image"));
                        result.put("desc",maps.get("desc"));
                    }
                }
                result.put("pushType","2");
                break;
            case 9 :
                Object parse9 = JSON.parse(value);
                if(parse9!=null){
                    ret =(Map) parse9;
                    result.put("val",ret.get("value"));
                    result.put("labelIds",ret.get("labelIds"));
                }
                result.put("type","image");
                result.put("pushType","1");
                break;
            case 10 :
                Object parse10 = JSON.parse(value);
                if(parse10!=null){
                    ret =(Map) parse10;
                    result.put("val",ret.get("value"));
                    result.put("labelIds",ret.get("labelIds"));
                }
                result.put("type","text");
                result.put("pushType","1");
                break;
            case 11 :
                Object parse11 = JSON.parse(value);
                if(parse11!=null){
                    ret =(Map) parse11;
                    result.put("val",ret.get("value"));
                    result.put("labelIds",ret.get("labelIds"));
                }
                result.put("type","video");
                result.put("pushType","1");
                break;
            case 12 :
                Object parse12 = JSON.parse(value);
                if(parse12!=null){
                    ret =(Map) parse12;
                    result.put("val",ret.get("value"));
                    result.put("labelIds",ret.get("labelIds"));
                }
                result.put("type","voice");
                result.put("pushType","1");
                break;
            case 13 :
                Object parse13 = JSON.parse(value);
                if(parse13!=null){
                    ret =(Map) parse13;
                    maps =survivalPushDao.getGoodsInfo(ret);
                    if(maps!=null){
                        if(!StringUtils.isEmpty(maps.get("goodsType"))){
                            goodsType = Integer.valueOf(maps.get("goodsType").toString());
                        }
                        value = this.getPagePathByGoodsType(maps,goodsType,orgId);
                        result.put("url",value);
                        result.put("title",maps.get("title"));
                        result.put("image",maps.get("image"));
                        result.put("desc",maps.get("desc"));
                        if(maps.get("labelIds")!=null){
                            String labelIds = maps.get("labelIds").toString();
                            labelIdsArr= Arrays.asList(labelIds.split(","));
                        }
                        result.put("labelIds",labelIdsArr);
                    }
                }
                result.put("pushType","2");
                break;
            case 14 :
                Object parse14 = JSON.parse(value);
                if(parse14!=null){
                    ret =(Map) parse14;
                    maps = survivalPushDao.getGoodsInfo(ret);
                    if(maps!=null){
                        if(!StringUtils.isEmpty(maps.get("goodsType"))){
                            goodsType = Integer.valueOf(maps.get("goodsType").toString());
                        }
                        value = this.getPagePathByGoodsType(maps,goodsType,orgId);
                        result.put("url",value);
                        result.put("title",maps.get("title"));
                        result.put("image",maps.get("image"));
                        result.put("desc",maps.get("desc"));
                        if(maps.get("labelIds")!=null){
                            String labelIds = maps.get("labelIds").toString();
                            labelIdsArr= Arrays.asList(labelIds.split(","));
                        }
                        result.put("labelIds",labelIdsArr);
                    }
                }
                result.put("pushType","2");
                break;
            case 15 :
                Object parse15 = JSON.parse(value);
                if(parse15!=null){
                    ret =(Map) parse15;
                    String shortUrl15="";
                    String articleId15 = "";
                    if(!StringUtils.isEmpty(ret.get("shortUrl"))){
                        shortUrl15 = ret.get("shortUrl").toString();
                    }
                    if(!StringUtils.isEmpty(ret.get("articleId"))){
                        articleId15 = ret.get("articleId").toString();
                    }
                    value = shortUrl15;
                    //Map labelNames= this.getArticleById(articleId15);
                    Map articleMap= this.getArticleById(articleId15);
                    String labelNames = articleMap.get("labelNames").toString();
                    List<String> labelIds = survivalPushDao.getLabelIds(labelNames,orgId);
                    result.put("url",value);
                    result.put("title",articleMap.get("title"));
                    result.put("image",articleMap.get("image"));
                    result.put("desc",articleMap.get("desc"));
                    result.put("labelIds",labelIds);
                }
                result.put("pushType","2");
                break;
            case 16 :
                Object parse16 = JSON.parse(value);
                if(parse16!=null){
                    ret =(Map) parse16;
                    maps = survivalPushDao.getEnrollInfo(ret);
                    if(maps!=null){
                        goodsType = 5;
                        value = this.getPagePathByGoodsType(maps,goodsType,orgId);
                        result.put("url",value);
                        result.put("title",maps.get("title"));
                        result.put("image",maps.get("image"));
                        result.put("desc",maps.get("desc"));
                        if(maps.get("labelIds")!=null){
                            String labelIds = maps.get("labelIds").toString();
                            labelIdsArr= Arrays.asList(labelIds.split(","));
                        }
                        result.put("labelIds",labelIdsArr);
                    }
                }
                result.put("pushType","2");
            default :
        }
        return result;
    }

    private Integer getTypeByValue(String value) {
        Object parse1 = JSON.parse(value);
        Integer resType = 1;
        if(parse1!=null){
            Map ret =(Map) parse1;
           Integer type =(Integer) ret.get("type");
            switch(type){
                case 0:
                    resType =1;
                    break;
                case 1:
                    resType =2;
                    break;
                case 2:
                    resType =7;
                    break;
                case 3:
                    resType =3;
                    break;
                case 4:
                    resType =4;
                    break;
                case 5:
                    resType =5;
                    break;
                case 6:
                    resType =8;
                    break;
                case 7:
                    resType =6;
                    break;
                    default:
                    break;
            }
        }
        return resType;
    }

    /**
     * 通过商品类型获取页面路径
     */
    private String getPagePathByGoodsType(Map map,Integer goodsType,String orgId) {
        String scrmWebUrl = systemProperties.getAcsScrmWebUrl();
        String token = survivalPushDao.getTokenByOrgId(orgId);
        String pagePath;
        String goodsId = map.get("goodsId").toString();
        String belongId = (String) map.get("belongId");
        String promotion = (String) map.get("promotion");
        boolean flag = false;
        if (StringUtils.isEmpty(belongId) && "0".equals(promotion)) {
            flag = true;
        }
        switch (goodsType) {
            case 3:
                // 内容
                pagePath = "mediaDetail/"+ goodsId + "?type=" + (flag ? "0" : "1");
                break;
            case 4:
                // 专栏
                pagePath = "columnDetail/"+ goodsId + "?type=" + (flag ? "0" : "1");
                break;
            case 5:
                // 报名
                pagePath = "activityForm/?enrollId=" + goodsId;
                break;
            default:
                // 商品
                pagePath = "goodsDetail/"+ goodsId + "?type=" + (flag ? "0" : "1");
                break;
        }
        String url = clientHost + "/personal/login?token=" + token + "&m=";
        try {
            String encode = URLEncoder.encode(pagePath, "UTF-8");
            String encode1 = URLEncoder.encode(scrmWebUrl + "userCenter.html?goto=" + encode, "UTF-8");
            url += encode1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 获取推送时间
     * @param survival
     * @return Date
     */
    public Date getDate(Map survival,Integer sendTime){
        String startTimeString = "";
        String endTimeString = "";
        if(!StringUtils.isEmpty(survival.get("startTime"))){
            startTimeString = survival.get("startTime").toString();
        }
        if(!StringUtils.isEmpty(survival.get("endTime"))){
            endTimeString = survival.get("endTime").toString();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date now =  new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.SECOND, sendTime);
            now = calendar.getTime();
            String dateString = formatter.format(now);
            String dayString = sdf.format(now);
            Date startTime = formatter.parse(startTimeString);
            Date endTime = formatter.parse(endTimeString);
            Date nowTime = formatter.parse(dateString);
            if(startTime.before(nowTime) && endTime.after(nowTime)){
                //返回第一天的开始时间
                String tesTimeStr = dayString+" "+formatter.format(now);
                Date d2 = sdf2.parse(tesTimeStr);
                return d2;
            }else if(nowTime.before(startTime)){
                //返回当前时间
                String tesTimeStr = dayString+" "+formatter.format(startTime);
                Date d2 = sdf2.parse(tesTimeStr);
                return d2;
            }else if(nowTime.after(endTime)){
                //返回第二天的开始时间
                Calendar c = Calendar.getInstance();
                Date nextDate = sdf.parse(dayString);
                c.setTime(nextDate);
                int day = c.get(Calendar.DATE);
                c.set(Calendar.DATE, day + 1);
                String nextDateString =sdf.format(c.getTime());
                String tesTimeStr = nextDateString+" "+formatter.format(startTime);
                Date d2 = sdf2.parse(tesTimeStr);
                return d2;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据文章id获取详情
     * @param articleId
     * @return
     */
    private Map getArticleById(String articleId){
        Map map = new HashMap();
        String labelNames = "";
        String title = " ";
        String image = " ";
        String desc = " ";
        String shortUrl = " ";
        try {
            String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_DETAIL;
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("newsId", articleId);
            JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
            String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
            LOGGER.info("getarticledetail===result===" + postres);
            if (null != postres) {
                Map res = (Map) JSON.parse(postres);
                if ("200".equals(res.get("code").toString())) {
                    if (res.get("data") == null) {
                        throw GlobalException.build("暂无文章数据");
                    }
                    if( res.get("data")!=null){
                        if(((Map) res.get("data")).get("newsLabel")!=null){
                            labelNames = ((Map) res.get("data")).get("newsLabel").toString();
                        }
                        if(((Map) res.get("data")).get("newsName")!=null){
                            title = ((Map) res.get("data")).get("newsName").toString();
                        }
                        if(((Map) res.get("data")).get("newsCover")!=null){
                            List nc = (List) ((Map) res.get("data")).get("newsCover");
                            if (null == nc || nc.size() == 0) {
                                image = defimg;
                            } else {
                                image = nc.get(0).toString();
                            }
                        }
                        if(((Map) res.get("data")).get("newsSummary")!=null){
                            desc = ((Map) res.get("data")).get("newsSummary").toString();
                        }
                        if(((Map) res.get("data")).get("shortUrl")!=null){
                            shortUrl = ((Map) res.get("data")).get("shortUrl").toString();
                        }

                        map.put("labelNames",labelNames);
                        map.put("title",title);
                        map.put("image",image);
                        map.put("desc",desc);
                        map.put("shortUrl",shortUrl);
                    }
                } else {
                    throw GlobalException.build("请求失败");
                }
            } else {
                throw GlobalException.build("请求失败");
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }


//    public static void main(String[] args) {
//            Map survival = new HashMap();
//            survival.put("startTime","06:00:00");
//            survival.put("endTime","18:00:00");
//            String startTimeString = "";
//            String endTimeString = "";
//            if(!StringUtils.isEmpty(survival.get("startTime"))){
//                startTimeString = survival.get("startTime").toString();
//            }
//            if(!StringUtils.isEmpty(survival.get("endTime"))){
//                endTimeString = survival.get("endTime").toString();
//            }
//            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            try {
//                Date now =  new Date();
//                String dateString = formatter.format(now);
//                String dayString = sdf.format(now);
//                Date startTime = formatter.parse(startTimeString);
//                Date endTime = formatter.parse(endTimeString);
//                Date nowTime = formatter.parse(dateString);
//                if(startTime.before(nowTime) && endTime.after(nowTime)){
//                    //返回第一天的开始时间
//                    String tesTimeStr = dayString+" "+formatter.format(now);
//                    Date d2 = sdf2.parse(tesTimeStr);
//                    System.out.println( d2);
//                    Long delaytime = d2.getTime()+(30*1000)-now.getTime();
//                    System.out.println(delaytime);
//                }else if(nowTime.before(startTime)){
//                    //返回当前时间
//                    String tesTimeStr = dayString+" "+formatter.format(startTime);
//                    Date d2 = sdf2.parse(tesTimeStr);
//                    System.out.println( d2);
//                    Long delaytime = d2.getTime()+(30*1000)-now.getTime();
//                    System.out.println(delaytime);
//                }else if(nowTime.after(endTime)){
//                    //返回第二天的开始时间
//                    Calendar c = Calendar.getInstance();
//                    Date nextDate = sdf.parse(dayString);
//                    c.setTime(nextDate);
//                    int day = c.get(Calendar.DATE);
//                    c.set(Calendar.DATE, day + 1);
//                    String nextDateString =sdf.format(c.getTime());
//                    String tesTimeStr = nextDateString+" "+formatter.format(startTime);
//                    Date d2 = sdf2.parse(tesTimeStr);
//                    System.out.println( d2);
//                    Long delaytime = d2.getTime()+(30*1000)-now.getTime();
//                    System.out.println(delaytime);
//                }
//
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//    }


    public static void main(String[] args) {
        String startTimeString = "09:00:00";
        String endTimeString = "10:50:00";
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now2 =  new Date();
        Date d3=  new Date();
        try {
            Date now =  new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.SECOND, 0);
            now = calendar.getTime();
            String dateString = formatter.format(now);
            String dayString = sdf.format(now);
            Date startTime = formatter.parse(startTimeString);
            Date endTime = formatter.parse(endTimeString);
            Date nowTime = formatter.parse(dateString);
            if(startTime.before(nowTime) && endTime.after(nowTime)){
                //返回第一天的开始时间
                String tesTimeStr = dayString+" "+formatter.format(now);
                Date d2 = sdf2.parse(tesTimeStr);
                d3 = d2;
            }else if(nowTime.before(startTime)){
                //返回当前时间
                String tesTimeStr = dayString+" "+formatter.format(startTime);
                Date d2 = sdf2.parse(tesTimeStr);
                d3 = d2;
            }else if(nowTime.after(endTime)){
                //返回第二天的开始时间
                Calendar c = Calendar.getInstance();
                Date nextDate = sdf.parse(dayString);
                c.setTime(nextDate);
                int day = c.get(Calendar.DATE);
                c.set(Calendar.DATE, day + 1);
                String nextDateString =sdf.format(c.getTime());
                String tesTimeStr = nextDateString+" "+formatter.format(startTime);
                Date d2 = sdf2.parse(tesTimeStr);
                d3 = d2;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(sdf2.format(d3));
        System.out.println(sdf2.format(now2));
        System.out.println(d3.getTime()-now2.getTime());
    }

    public void saveShareCache(String pid, String actType, String orgId, String customerId) {
        LOGGER.info("进入任务赠送=======pid->"+pid+"  actType->"+actType+"  customerId->"+customerId);
        List<Map<String,Object>> list = scoreActiveCacheDao.getScoreAct("share",actType,orgId);
        if(null!=list && list.size()>0){
            for(Map<String,Object> li : list){
                String type;
                if("1".equals(li.get("type").toString())){
                    type = "score";
                }else{
                    type = "growth";
                }
                String shareKey = "";
                switch (actType){
                    case "open":
                        shareKey = scoreActiveCacheService.shareKey+"open_";
                        break;
                    case "subscribe":
                        shareKey = scoreActiveCacheService.shareKey+"subscribe_";
                        break;
                    case "register":
                        shareKey = scoreActiveCacheService.shareKey+"register_";
                        break;
                        default:break;
                }
                if(!StringUtils.isEmpty(shareKey)) {
                    Map<String, Object> customerById = vipCustomerLogDao.getCustomerById(pid);
                    if (null != customerById && !pid.equals(customerId)) {
                        //判断该用户是否已经被送过
                        Boolean member = stringRedisTemplate.opsForSet().isMember(shareKey + "_"+type + "_" +"given", customerId);
                        if (null == member || !member) {
                            String key = scoreActiveCacheService.shareKey + getToday() + "_" + actType + "_" + orgId + "_" + pid + "_" + type;
                            stringRedisTemplate.opsForValue().increment(key, 1L);
                            stringRedisTemplate.expire(key, 30, TimeUnit.DAYS);
                            stringRedisTemplate.opsForSet().add(shareKey + "_"+type + "_" +"given", customerId);
                        }
                    }
                }
            }
        }
    }

    private String getToday(){
        SimpleDateFormat format = new SimpleDateFormat(CalendarUtils.DAY_FORMAT);
        return format.format(CalendarUtils.getToday());
    }
}
